package dyy.zc.campuspay.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cn.bmob.v3.BmobInstallation;
import cn.bmob.v3.datatype.BmobFile;
import dyy.zc.campuspay.R;
import dyy.zc.campuspay.application.MyApplication;
import dyy.zc.campuspay.base.BaseFragment;
import dyy.zc.campuspay.bean.Account;
import dyy.zc.campuspay.bean.OrderInfo;
import dyy.zc.campuspay.bean.Pickers;
import dyy.zc.campuspay.constant.Constants;
import dyy.zc.campuspay.listener.OnItemClickListener;
import dyy.zc.campuspay.ui.activity.BillDetailActivity;
import dyy.zc.campuspay.ui.adapter.QueryAdapter;
import dyy.zc.campuspay.utils.BmobUtils;
import dyy.zc.campuspay.utils.DividerItemDecoration;
import dyy.zc.campuspay.utils.PieChart;
import dyy.zc.campuspay.utils.PieDataEntity;
import dyy.zc.campuspay.utils.Utils;
import dyy.zc.campuspay.views.EmptyView;
import dyy.zc.campuspay.views.PickerScrollView;
import dyy.zc.campuspay.views.Popwindows;

/**
 *
 * Created by yyuand on 2017.3.14.
 */

public class QueryFragment extends BaseFragment implements View.OnClickListener {
    private TextView tvTitle;
//    private static QueryAdapter adapter;
//    private RecyclerView recyclerView;
    private BmobUtils bmobUtils;
    private  List<OrderInfo> list = new ArrayList<>();
    private  List<OrderInfo> list_all = new ArrayList<>();
    private List<PieDataEntity> dataEntities = new ArrayList<>();
    private TextView yuefen,chaxun;
    private PieChart pieChart;
//    private static int startIndex = 0;
//    private static int pageSize = 11;
//    private static boolean isRequestData = true;
//    private static MaterialRefreshLayout materialRefreshLayout;
    private int orderTypeNum;
//    private static EmptyView emptyView;
    private Popwindows popwindows;
    private String year = "1970";
    private String month = "1";
    private View view;
    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == Constants.ResultCode.SUCCESS){
                list_all.addAll(BmobUtils.list_order);
//                if (startIndex == 0) {
//                    list_all.clear();
//                }
//                //如果没有请求到数据，则关闭网络请求
//                if (BmobUtils.list_order.size() == 0) {
//                    isRequestData = false;
//                } else if (BmobUtils.list_order.size() < pageSize) {//返回不足一次请求的量
//                    list_all.addAll(BmobUtils.list_order);
//                    isRequestData = false;
//                } else {
//                    BmobUtils.list_order.remove(BmobUtils.list_order.size() - 1);
//                    list_all.addAll( BmobUtils.list_order);
//                    isRequestData = true;
//                }
                changeData();

            }
        }
    };
private double zhichu = 0;//支出
private double shouru = 0;//收入
    public  void check(){
        list.clear();
        Log.e("check",list.size()+"");
        Account account = MyApplication.getInstance().readLoginUser();
        for (OrderInfo o:list_all){
            if (o.getId().equals(account.getId())){
                list.add(o);
            }
        }
        for (OrderInfo orderInfo:list){
            if (orderInfo.isType()){
                shouru +=Double.valueOf(orderInfo.getPrice());
            }else {
                zhichu += Double.valueOf(orderInfo.getPrice());
            }
        }
    }

    private void changeData() {
        check();
        //判断如果没有数据的话，则显示空提示
//        if (list.size() == 0) {
//            emptyView.setNotify("暂无订单");
//        } else {
//            emptyView.setEmptyViewGone();
//        }
        Log.e("list",list.size()+"");
        if (list.size() !=0){
            pieChart.setVisibility(View.VISIBLE);
            dataEntities.clear();
            PieDataEntity entity1 = new PieDataEntity("支出",(float) zhichu,0xffff5001);
            PieDataEntity entity2 = new PieDataEntity("收入",(float) shouru,0xff11b14d);
            dataEntities.add(entity1);
            dataEntities.add(entity2);
            pieChart.setDataList(dataEntities);
        }else {
            pieChart.setVisibility(View.INVISIBLE);
        }

//        adapter.addList(list);
//        adapter.notifyDataSetChanged();
//        materialRefreshLayout.finishRefreshLoadMore();
//        materialRefreshLayout.finishRefresh();
    }

    @Override
    protected View onCreateViews(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.fragment_query,container,false);
        initView(view);
        initData();
        bind();
        return view;
    }


    private void initView(View v) {
//        emptyView = new EmptyView(v);
//        materialRefreshLayout = Utils.findViewsById(v, R.id.sallerList_refresh);
        tvTitle = Utils.findViewsById(v,R.id.top_tv_title);
//        recyclerView = Utils.findViewsById(v,R.id.recycler);
        yuefen = Utils.findViewsById(v,R.id.tv_bill);
        chaxun = Utils.findViewsById(v,R.id.tv_search_month);
        pieChart = Utils.findViewsById(v,R.id.pieChart);
    }

    private void initData() {
        tvTitle.setText("消费查询");
        bmobUtils = new BmobUtils(getActivity());
        bmobUtils.queryOrderInfo();
    }


    private void bind() {
        chaxun.setOnClickListener(this);
//        adapter = new QueryAdapter(getActivity(),list);
//        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//        recyclerView.setItemAnimator(new DefaultItemAnimator());
//        DividerItemDecoration decoration = new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL_LIST);
//        decoration.setDivider(R.drawable.divider_shape);
//        recyclerView.addItemDecoration(decoration);
//        recyclerView.setAdapter(adapter);
//        adapter.setOnItemClickListener(new OnItemClickListener() {
//            @Override
//            public void onItemClick(int position) {
//                Intent intent = new Intent(getActivity(), BillDetailActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putSerializable("order",list.get(position));
//                intent.putExtras(bundle);
//                startActivity(intent);
//            }
//        });

//        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
//            @Override
//            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
//                startIndex = 0;
//                yuefen.setText("全部账单");
//                bmobUtils.queryOrderInfo();
//            }
//
//            @Override
//            public void onRefreshLoadMore(final MaterialRefreshLayout materialRefreshLayout) {
//                if (isRequestData) {
//                    startIndex += pageSize - 1;
//                    list_all.clear();
//                    yuefen.setText("全部账单");
//                    bmobUtils.queryOrderInfo();
//                    return;
//                }
//                new Handler().postDelayed(new Runnable() {
//
//                    @Override
//                    public void run() {
//                        // TODO Auto-generated method stub
//                        materialRefreshLayout.finishRefreshLoadMore();
//                    }
//                }, 1000);
//            }
//        });
    }

    @Override
    public void onClick(View v) {
        popwindows = new Popwindows(getActivity(),chaxunListener,yearListener,monthListener);
        popwindows.showAtLocation(view, Gravity.BOTTOM,0,0);
        year = "1970";
        month = "1";
    }

    private View.OnClickListener chaxunListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            popwindows.dismiss();
            yuefen.setText(year+"-"+month);
            classify();
        }
    };

   private void classify(){
       List<OrderInfo> temp = new ArrayList<>();
       List<OrderInfo> temp_list = new ArrayList<>();
       temp_list.clear();
       temp_list.addAll(list);
       temp.clear();
       for (OrderInfo orderInfo:temp_list){
           String date = orderInfo.getCreatedAt();
           String[] str = date.split("-");
           String str_year = str[0];
           String str_month = str[1];

           int pick_year = Integer.valueOf(year);
           int pick_month = Integer.valueOf(month);
           int year_o = Integer.valueOf(str_year);
           int month_o = Integer.valueOf(str_month);
           Log.e("str_year",pick_year+"---"+pick_month);
           Log.e("year",year_o+"---"+month_o);
           if (pick_month == month_o && pick_year == year_o){
               Log.e("str_year",str_year+"---"+year);
               temp.add(orderInfo);
           }
       }
       if (temp.size() !=0){
           pieChart.setVisibility(View.VISIBLE);
           shouru = 0;
           zhichu = 0;
           for (OrderInfo orderInfo:temp){
               if (orderInfo.isType()){
                   shouru +=Double.valueOf(orderInfo.getPrice());
               }else {
                   zhichu += Double.valueOf(orderInfo.getPrice());
               }
           }
           dataEntities.clear();
           PieDataEntity entity1 = new PieDataEntity("支出",(float) zhichu,0xffff5001);
           PieDataEntity entity2 = new PieDataEntity("收入",(float) shouru,0xff11b14d);
           dataEntities.add(entity1);
           dataEntities.add(entity2);
           pieChart.setDataList(dataEntities);
       }else {
           pieChart.setVisibility(View.INVISIBLE);
       }

       //判断如果没有数据的话，则显示空提示
//       if (temp.size() == 0) {
//           emptyView.setNotify("暂无订单");
//       } else {
//           emptyView.setEmptyViewGone();
//       }
//       adapter.addList(temp);
//       adapter.notifyDataSetChanged();
   }

    private PickerScrollView.onSelectListener yearListener = new PickerScrollView.onSelectListener() {
        @Override
        public void onSelect(Pickers pickers) {
            year = pickers.getShowConetnt();
        }
    };
    private PickerScrollView.onSelectListener monthListener = new PickerScrollView.onSelectListener() {
        @Override
        public void onSelect(Pickers pickers) {
            month = pickers.getShowConetnt();
        }
    };
}
